package com.hancai.config.handler;

import com.hancai.constant.Constants;
import com.hancai.model.TUser;
import com.hancai.result.CodeEnum;
import com.hancai.result.R;
import com.hancai.service.RedisService;
import com.hancai.util.JSONUtils;
import com.hancai.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 涵菜
 * @version 1.0
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisService redisService;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //退出成功，执行该方法，在该方法中返回json给前端就行了
        TUser tUser=(TUser) authentication.getPrincipal();
        //需要把redis中的登录token删掉(用户的JWT)
        redisService.removeValue(Constants.REDIS_JWT_KEY+tUser.getId());
        R result=R.OK(CodeEnum.USER_LOGOUT);
        //把R对象转换为JSON
        String resultJSON= JSONUtils.toJSON(result);
        //把R以json形式返回给前端
        ResponseUtils.write(response,resultJSON);
    }
}
